/**
 * @modal: 新增拆分策略
 */
import { useState, useEffect } from 'react';
import CommonInput from '@/pages/OrderModule/common/components/CommonInput';
import CommonInputNumber from '@/pages/OrderModule/common/components/CommonInputNumber';
import DebounceMultipleSelect from '@/components/DebounceMultipleSelect';
import GoodsSelectModal from '@/pages/OrderModule/common/bizcomponents/GoodsSelectModal';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import { QuestionCircleOutlined } from '@ant-design/icons';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Col, Form, Radio, Row, Select, InputNumber, message, Popover } from 'antd';
import styles from './index.module.less';
import CommonLoading from '@/components/CommonLoading';
import Api from '../../service';
import { uniqBy } from 'lodash';
import Iconfont from "@/components/IconFont";

const spiltOrderOptions = [
	{ label: '有拆分历史的订单允许继续拆单', value: true },
	{ label: '有拆分历史的订单不允许继续拆单', value: false },
]

const mergeOrderOptions = [
	{ label: '有合单历史的订单允许继续拆单', value: true },
	{ label: '有合单历史的订单不允许继续拆单', value: false },
]

const searchOptions = [
	{ label: '精准查询', value: 1 },
	{ label: '模糊查询', value: 2 }
]

function AddSplittingStrategy(props) {
	const { id, handleOk, handleCancel } = props;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [form] = Form.useForm();
	const [goodsSelectInfo, setGoodsSelectInfo] = useState({
		type: '',
		name: '',
		visible: false,
		spuCodes: [],
		goodsCodes: [],
		notParticipateSpuCodes: [],
		notParticipateGoodsCodes: [],
	})
	const type = Form.useWatch('type', form);
	const [itemInfo, setItemInfo] = useState({
		type: 1,
		splitCondition: true,
		mergedCondition: true,
		participatingOrder: 1,
		spuCodeSearch: 1,
		goodsCodeSearch: 1,
		notParticipateSpuCodeSearch: 1,
		notParticipateGoodsCodeSearch: 1,
	});

	useEffect(() => {
		setOpen(true);
		if (id) {
			querySpitStrategyDetail();
		}
	}, [])

	//获取策略列表
	const querySpitStrategyDetail = async () => {
		setLoading(true);
		const { success, data } = await Api.spitStrategyDetail({ id });
		if (success) {
			const ruleDetail = data.ruleDetail;
			const obj = {
				...data,
			}
			if (ruleDetail) {
				const obj1 = JSON.parse(ruleDetail);
				setItemInfo({
					...obj,
					...obj1,
					goodsCodes: obj1.goodsCodes ? obj1.goodsCodes.join() : undefined,
					spuCodes: obj1.spuCodes ? obj1.spuCodes.join() : undefined,
					notParticipateGoodsCodes: obj1.notParticipateGoodsCodes ? obj1.notParticipateGoodsCodes.join() : undefined,
					notParticipateSpuCodes: obj1.notParticipateSpuCodes ? obj1.notParticipateSpuCodes.join() : undefined,
					ruleDetail: undefined,
					spuCodeSearch: obj1.spuCodeSearch || 1,
					goodsCodeSearch: obj1.goodsCodeSearch || 1,
					notParticipateSpuCodeSearch: obj1.notParticipateSpuCodeSearch || 1,
					notParticipateGoodsCodeSearch: obj1.notParticipateGoodsCodeSearch || 1,
				})
			} else {
				setItemInfo(data);
			}
			let timer = setTimeout(() => {
				form.resetFields();
				fetchStoreList();
				clearTimeout(timer);
				timer = undefined;
			})
		}
		setLoading(false);
	}

	const onOk = async () => {
		form.validateFields().then(value => {
			updateSpitStrategy(value);
		}).catch(err => console.log(err));
	}

	//编辑策略信息
	const updateSpitStrategy = async (val) => {
		const params = {
			id,
			type: val.type,
			name: val.name,
			level: val.level,
			participatingOrder: val.participatingOrder,
			mergedCondition: val.mergedCondition,
			splitCondition: val.splitCondition,
		};

		if (params.type == 1) {
			const ruleDetail = {};
			ruleDetail.goodsNum = val.goodsNum;
			params.ruleDetail = JSON.stringify(ruleDetail);
		}

		if (params.type == 3) {
			const ruleDetail = {};
			ruleDetail.storeIds = val.storeIdsArr ? val.storeIdsArr.map(v => v.value) : undefined;
			ruleDetail.storeIdsArr = val.storeIdsArr;
			params.ruleDetail = JSON.stringify(ruleDetail);
		}

		if (params.type == 5) {
			const ruleDetail = {};
			ruleDetail.goodsCodes = val.goodsCodes ? val.goodsCodes.split(',') : undefined;
			ruleDetail.spuCodes = val.spuCodes ? val.spuCodes.split(',') : undefined;
			ruleDetail.notParticipateGoodsCodes = val.notParticipateGoodsCodes ? val.notParticipateGoodsCodes.split(',') : undefined;
			ruleDetail.notParticipateSpuCodes = val.notParticipateSpuCodes ? val.notParticipateSpuCodes.split(',') : undefined;
			ruleDetail.orderItemMaxNum = val.orderItemMaxNum;
			ruleDetail.spuCodeSearch = val.spuCodeSearch;
			ruleDetail.goodsCodeSearch = val.goodsCodeSearch;
			ruleDetail.notParticipateSpuCodeSearch = val.notParticipateSpuCodeSearch;
			ruleDetail.notParticipateGoodsCodeSearch = val.notParticipateGoodsCodeSearch;
			params.ruleDetail = JSON.stringify(ruleDetail);
		}

		if (params.type == 6) {
			const ruleDetail = {};
			ruleDetail.maxWeight = val.maxWeight;
			ruleDetail.minWeight = val.minWeight;
			params.ruleDetail = JSON.stringify(ruleDetail);
		}
		setLoading(true);

		const updateApi = id ? Api.updateSpitStrategy : Api.addSpitStrategy
		const { success } = await updateApi(params);
		if (success) {
			message.success('操作成功');
			setIsOk(true);
			setOpen(false);
		}
		setLoading(false);
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	//获取供应商列表
	function fetchStoreList(storeName) {
		const val = form.getFieldValue('storeIdsArr');
		const ininData = val || [];
		return new Promise(async (resolve) => {
			const params = {
				size: 50,
				current: 1,
				querySrc: 1,
				storeName
			}
			const { data, success } = await Api.queryListByStoreName(params);
			if (success && data?.records.length) {
				const newArr = [];
				data.records.map((item) => {
					newArr.push({
						label: item.storeName,
						value: item.storeId,
					});
				});
				resolve(uniqBy([...ininData, ...newArr], 'value'));
			} else {
				resolve([...ininData]);
			}
		});
	}
	//校验订单商品数量
	const checkGoodsNum = (_, value) => {
		if (type == 1) {
			if (value) {
				return Promise.resolve();
			} else {
				return Promise.reject(new Error('请输入商品数量'));
			}
		}
		return Promise.resolve();
	};

	//校验拆单重量
	const checkMaxWeight = (_, value) => {
		if (type == 6) {
			if (value) {
				const val = form.getFieldValue('minWeight');
				if (val && val >= value) {
					return Promise.reject(new Error('拆单重量必须大于最小重量'));
				}
				return Promise.resolve();
			} else {
				return Promise.reject(new Error('请输入拆单重量'));
			}
		}
		return Promise.resolve();
	};

	//校验拆单重量
	const checkSpuCodes = (_, value) => {
		if (type == 5) {
			if (!value) {
				const val = form.getFieldValue('spuCodes');
				if (!val) {
					return Promise.reject(new Error('商品编码和款式编码至少填写一项'));
				}
				return Promise.resolve();
			}
			return Promise.resolve();
		}
		return Promise.resolve();
	};

	const showModal = (name, type) => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			type,
			name,
			visible: true
		})
	}

	//选择商品
	const handleGoodsSelect = data => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			[goodsSelectInfo.name]: data,
			visible: false
		})
		const val = ['spuCodes', 'notParticipateGoodsCodes'].includes(goodsSelectInfo.name) ? data.map(v => v.spuCode) : data.map(v => v.skuCode);
		form.setFieldsValue({
			[goodsSelectInfo.name]: val.join()
		})
	}

	const changeGoodsModalProps = {
		type: goodsSelectInfo.type,
		submitCallback(changedArr) {
			handleGoodsSelect(changedArr);
		},
		handleCancel() {
			setGoodsSelectInfo({
				...goodsSelectInfo,
				visible: false
			})
		},
		setSelectedRows(data, rowKey) {
			return goodsSelectInfo[goodsSelectInfo.name].map(v => v[rowKey]) || [];
		}
	}

	return (
		<CommonModal title={{ title: '智能拆分策略' }} open={open} afterClose={afterClose} width="600px" onOk={onOk} onCancel={onCancel}>
			<Form name="basic" initialValues={itemInfo} form={form} autoComplete="off" layout="horizontal" labelAlign="right">
				<Form.Item name="name" rules={[{ required: true, message: '请输入策略名称' }]}>
					<CommonInput placeholder="必填，请输入策略名称" maxLength={20} aria-required />
				</Form.Item>
				<Form.Item name="level" rules={[{ required: true, message: '请输入优先级' }]}>
					<CommonInputNumber placeholder="必填，优先级" min={0} max={999} precision={0} aria-required />
				</Form.Item>
				<SubTitle className={styles.title} title="策略类型" as="s2" symbol />
				<Form.Item name="type">
					<Radio.Group className={styles.radio_group}>
						<Row style={{ alignItems: 'baseline' }}>
							<Col span={6}>
								<Radio value={1}>按数量拆分</Radio>
							</Col>
							<Col span={18}>
								<Form.Item name="goodsNum" rules={[{ validator: checkGoodsNum }]}>
									<CommonInputNumber placeholder="订单商品数量" min={1} precision={0} aria-required />
								</Form.Item>
							</Col>
						</Row>
						<Row align="middle" style={{ marginBottom: '12px' }}>
							<Col span={24}>
								<Radio value={2}>按退款状态拆分</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（拆分成一个包含退款中的商品和一个不包含退款中的商品）
								</Typography>
							</Col>
						</Row>
						<Row align="middle" gutter={[10, 10]} style={{ marginBottom: '12px' }}>
							<Col span={24}>
								<Radio value={3} >按供应商/供应商拆单</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（相同的供应商商品，会拆在同一个订单里，组合商品除外）
								</Typography>
								<Popover content={<div>
									<div>指定供应商，则对指定供应商的商品拆在同一个新订单里</div>
									<div>若未指定，则所有供应商商品都支持拆分</div>
								</div>}>
									<QuestionCircleOutlined className={styles.helpIcon} />
								</Popover>
							</Col>
							{
								type == 3 ?
									<Col span={24}>
										<Form.Item name="storeIdsArr" style={{ marginLeft: '25px' }} extra={<div className={styles.formDesc}>指定供应商，则对指定供应商的商品进行拆分；若未指定，则对所有供应商进行拆分</div>}>
											<DebounceMultipleSelect
												showSearch
												maxTagCount={2}
												mode="multiple"
												placeholder="请选择供应商"
												needFetchFirst
												fetchOptions={fetchStoreList}
												allowClear
											/>
										</Form.Item>
									</Col> : null
							}

						</Row>
						<Row align="middle" style={{ marginBottom: '12px' }}>
							<Col span={24}>
								<Radio value={4}>按仓库拆单</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（不同仓库的商品拆分在不同订单里）
								</Typography>
								<Popover content={<div>
									<div>释义：</div>
									<div>1、商品在哪个分仓库存添加了商品就算关联了该仓库</div>
									<div>2、商品如果在多个分仓库存都有数据，则按照“正品可用库存”最多的优先关联</div>
									<div>3、拆分后，不同商品的订单，仓库显示关联的仓库</div>
								</div>}>
									<QuestionCircleOutlined className={styles.helpIcon} />
								</Popover>
							</Col>
						</Row>
						<Row align="middle" gutter={[10, 10]} style={{ marginBottom: '12px' }}>
							<Col span={24}>
								<Radio value={5}>指定商品拆单</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（所有的指定商品拆分到同一个订单里）
								</Typography>
							</Col>
						</Row>
						{
							type == 5 ?
								<>
									<Row align="middle" gutter={[10, 10]}>
										<Col span={24}>
											<div className={styles.item_padding} style={{ display:'flex', alignItems: 'baseline'}}>
												<Form.Item name="spuCodes" style={{ marginBottom: '4px', marginRight: '8px', flex: 1 }} >
													<CommonInput placeholder="请输入指定款式编码，多个款式编码逗号隔开" suffix={<Iconfont type="icondirect-input" onClick={() => showModal('spuCodes', 'AccordingStyle')} />} />
												</Form.Item>
												<Form.Item name="spuCodeSearch">
													<Select  style={{ width: 100 }} options={searchOptions} />
												</Form.Item>
											</div>
										</Col>
										<Col span={24}>
											<div className={styles.item_padding} style={{ display:'flex', alignItems: 'baseline'}}>
												<Form.Item name="goodsCodes" style={{ flex: 1, marginRight: '8px', }} rules={[{ validator: checkSpuCodes }]} extra={<div className={styles.formDesc}>以上2个字段是“或”的关系，至少填写一项</div>}>
													<CommonInput placeholder="请输入指定商品编码，多个商品编码逗号隔开" suffix={<Iconfont type="icondirect-input" onClick={() => showModal('goodsCodes', 'NoNumberInput')} />} />
												</Form.Item>
												<Form.Item name="goodsCodeSearch">
													<Select  style={{ width: 100 }} options={searchOptions} />
												</Form.Item>
											</div>
										</Col>
									</Row>
									<Row style={{ alignItems: 'baseline' }}>
										<Col span={14}>
											<Typography className={styles.item_padding} style={{ fontSize: '14px' }} as="s1">
												拆分出来的所有订单，每单的最大数量为
											</Typography>
										</Col>
										<Col span={10}>
											<Form.Item name="orderItemMaxNum" extra={<div className={styles.formDesc}>超过这个数量的订单，将会再次进行拆分</div>}>
												<InputNumber placeholder="请输入数量" controls={false} min={0} max={9999} precision={0} suffix="kg" />
											</Form.Item>
										</Col>
									</Row>
									<Row>
										<Col span={24}>
											<div className={styles.item_padding} style={{ display:'flex', alignItems: 'baseline'}}>
												<Form.Item name="notParticipateSpuCodes" style={{ flex: 1, marginRight: '8px', }}>
													<CommonInput placeholder="请输入不参加单独拆分的款式编码，多个款式编码逗号隔开" suffix={<Iconfont type="icondirect-input" onClick={() => showModal('notParticipateSpuCodes', 'NoNumberInput')} />} />
												</Form.Item>
												<Form.Item name="notParticipateSpuCodeSearch">
													<Select  style={{ width: 100 }} options={searchOptions} />
												</Form.Item>
											</div>
										</Col>
										<Col span={24}>
											<div className={styles.item_padding} style={{ display:'flex', alignItems: 'baseline'}}>
												<Form.Item name="notParticipateGoodsCodes" style={{ flex: 1, marginRight: '8px', }} extra={<div className={styles.formDesc}>以上2个字段是“或”的关系，订单只要含有上述编码，就不会参与拆分</div>}>
													<CommonInput placeholder="请输入不参加单独拆分的商品编码，多个商品编码逗号隔开" suffix={<Iconfont type="icondirect-input" onClick={() => showModal('notParticipateGoodsCodes', 'NoNumberInput')} />} />
												</Form.Item>
												<Form.Item name="notParticipateGoodsCodeSearch">
													<Select  style={{ width: 100 }} options={searchOptions} />
												</Form.Item>
											</div>
										</Col>
									</Row>
								</>
								: null
						}
						<Row align="middle" gutter={[10, 10]}>
							<Col span={24}>
								<Radio value={6}>按重量拆分</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（按照设置的重量拆分）
								</Typography>
							</Col>
							{
								type == 6 ?
									<>
										<Col span={24}>
											<div className={styles.item_padding}>
												<Form.Item name="maxWeight" style={{ marginBottom: '4px' }} rules={[{ validator: checkMaxWeight }]}>
													<InputNumber placeholder="必填，请输入拆分最大重量" controls={false} style={{ width: '100%' }} addonAfter="kg" min={0.001} max={999} precision={3} suffix="kg" aria-required />
												</Form.Item>
											</div>
										</Col>
										<Col span={24}>
											<div className={styles.item_padding} >
												<Form.Item name="minWeight">
													<InputNumber placeholder="请输入拆分最小重量" controls={false} style={{ width: '100%' }} addonAfter="kg" min={0.001} max={999} precision={3} suffix="kg" />
												</Form.Item>
											</div>
										</Col>
									</> : null
							}
						</Row>
					</Radio.Group>
				</Form.Item>
				<SubTitle className={styles.title1} title="参与订单" as="s2" symbol />
				<Form.Item name="participatingOrder">
					<Radio.Group className={styles.radio_group}>
						<Row align="middle">
							<Col span={24}>
								<Radio value={1} style={{ marginBottom: '16px' }}>订单列表勾选的订单</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（只限待审核）
								</Typography>
							</Col>
							<Col span={24}>
								<Radio value={2}>所有符合条件的订单</Radio>
								<Typography as="s1" color="rgba(153, 153, 153, 1)">
									（根据筛选出来的订单，只限待审核）
								</Typography>
							</Col>
						</Row>
					</Radio.Group>
				</Form.Item>
				<Row align="middle" gutter={[10, 10]}>
					<Col span={24}>
						<div className={styles.item_padding}>
							<Form.Item name="splitCondition" style={{ marginBottom: '4px' }}>
								<Select options={spiltOrderOptions} placeholder="请选择" />
							</Form.Item>
						</div>
					</Col>
					<Col span={24}>
						<div className={styles.item_padding}>
							<Form.Item name="mergedCondition">
								<Select options={mergeOrderOptions} placeholder="请选择" />
							</Form.Item>
						</div>
					</Col>
				</Row>
			</Form>
			{goodsSelectInfo.visible && <GoodsSelectModal {...changeGoodsModalProps} />}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AddSplittingStrategy;
